﻿using System.Security.Claims;
using BPanel.Core.Extensions;
using BPanel.Web.ViewModels.Auth;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace BPanel.Web.Controllers;

[Authorize]
public class AuthController : Controller
{
    private readonly IFreeSql _freeSql;

    /// <summary>
    /// AuthController
    /// </summary>
    /// <param name="freeSql"></param>
    public AuthController(IFreeSql freeSql)
    {
        _freeSql = freeSql;
    }

    /// <summary>
    /// 登录页面
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    public IActionResult Login()
    {
        return View();
    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="loginModel"></param>
    /// <returns></returns>
    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginModel loginModel)
    {
        var system = await _freeSql.Select<BPanel.Database.Entities.System>().Where(c => c.Username == loginModel.Username).FirstAsync();
        if (system == null)
        {
            ViewData["Message"] = "账号或密码不正确";
            return View();
        }

        if (system.Password != loginModel.Password.Md5())
        {
            ViewData["Message"] = "账号或密码不正确";
            return View();
        }

        var claims = new List<Claim>() //身份验证信息
        {
            new(ClaimTypes.Name, $"{loginModel.Username}"),
        };

        var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "bpanel"));
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
        {
            ExpiresUtc = DateTime.UtcNow.AddDays(1), //过期时间：1天
        });

        var redirectUrl = string.IsNullOrWhiteSpace(loginModel.ReturnUrl) ? "/home/index" : loginModel.ReturnUrl;

        return base.Redirect(redirectUrl);
    }

    /// <summary>
    /// 退出登录
    /// </summary>
    public async Task Logout()
    {
        await HttpContext.SignOutAsync();
    }
}